package com.sunshuo.springsecuritydemo.controller;

import com.sunshuo.springsecuritydemo.pojo.RoleMenu;
import com.sunshuo.springsecuritydemo.service.RoleMenuService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName RoleMenuController
 * @Description TODO
 * @Author sunshuo
 */
@Controller
@RequestMapping("/role_menu")
public class RoleMenuController {

    private RoleMenuService roleMenuService;

    @Autowired
    public void setRoleMenuService(RoleMenuService roleMenuService) {
        this.roleMenuService = roleMenuService;
    }

    @RequestMapping("/update_relation")
    @ResponseBody
    public String updateRelation(String roleId, String roleMenus) {
        JSONObject results = new JSONObject();
        try {
            List<RoleMenu> roleMenuList = new ArrayList<>();
            JSONArray roleMenuArray = new JSONArray(roleMenus);
            for (int i = 0; i < roleMenuArray.length(); i++) {
                final JSONObject jsonObject = roleMenuArray.getJSONObject(i);
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(jsonObject.getString("id"));
                roleMenuList.add(roleMenu);
            }
            roleMenuService.updateRelations(roleId, roleMenuList);
            results.put("code", 200);
            return results.toString();
        } catch (Exception e) {
            results.put("code", 500);
            results.put("message", "更新失败");
        }
        return results.toString();
    }

}
